<script setup lang='ts'>
import { applyPlatList, useApplyAudit, useApplyProcess } from '@fl/api/add-elevator-api'
import type { applyUpdateParam } from '@fl/api/add-elevator-api/model/apply-model'
import { SubmitBtn } from '@fl/components'
import FlUpload from '@fl/components/fl-upload.vue'
import dayjs from 'dayjs'
import { cloneDeep } from 'lodash-es'
import type { PlusFormGroupRow } from 'plus-pro-components'
import { useDicts } from '../hooks/use-dicts'
import showMap from '../../history/components/map.vue'

const visible = defineModel<boolean>('visible', { required: true })
const id = defineModel<string>('id', { required: true })
const isEdit = defineModel<boolean>('isedit', { required: true })
const position = defineModel<any>('position', { required: false })
const status = defineModel<string>('status', { required: true }) // 上一个已完成的节点
const currentStatus = ref<number>(0) // 当前点击节点
const currentFiles = ref<any>([])
const active = ref<number>(0) // 进行中节点索引：已完成节点下一级的索引

const formRef = ref()
const stepData = ref<any>([])
const platOptions = ref<any>([])
const titleStr1 = ref<string>('可行性分析')
const titleStr2 = ref<string>('相关资料上传（点击文件名直接下载模版）')
const labelStr = ref<string>('取得可行性分析意见告知书时间')

const { useDict } = useDicts()

const disabled = computed(() => {
    return currentStatus.value <= Number(status.value) || !isEdit.value
})

const title = computed(() => {
    return useDict('ProgressButton', status.value)
})

const initialState = {
    result: 1, // 审核结果是否通过：前端0/1，后端true/false
    refuseType: 1,
    remark: '', // 可信性-其他
    info: '',
    formDate: '', // 日期
    file: [],
    budget: undefined, // 预算 - 联合审查
    agentFlag: 1, // 是否代办 - 联合审查
    agentName: '', // 代办名称 - 联合审查
    entranceFlag: 1, // 是否平层入户-联合审查
    brand: '', // 电梯品牌 - 电梯使用登记
    useCompany: '', // 电梯使用单位 - 电梯使用登记
    repairCompany: '', // 电梯维保单位 - 电梯使用登记
    elevatorCode: '',
}
const state = ref<applyUpdateParam>(cloneDeep(initialState))

watch(currentStatus, (val) => {
    if (val === 30) {
        // 完成业主意见征询
        titleStr1.value = '完成业主意见征询'
        titleStr2.value = '相关资料上传（点击文件名直接下载模版）'
        labelStr.value = '完成业主意见征询时间'
    }
    else if (val === 40) {
        // 可行性分析
        titleStr1.value = '可行性分析'
        titleStr2.value = '相关资料上传（点击文件名直接下载模版）'
        labelStr.value = '取得可行性分析意见告知书时间'
    }
    else if (val === 50) {
        // 联合审查
        titleStr1.value = '联合审查'
        titleStr2.value = '相关资料上传'
        labelStr.value = '取得联合审查批准意见书时间'
    }
    else if (val === 60) {
        // 电梯使用登记
        titleStr2.value = '电梯使用登记'
        labelStr.value = '取得电梯使用登记时间'
    }
    else if (val === 70) {
        // 竣工验收登记
        titleStr2.value = '相关资料上传'
        labelStr.value = '取得电梯竣工意见验收表时间'
    }
    else if (val === 80) {
        // 档案归档
        titleStr2.value = '档案归档'
        labelStr.value = '取得档案归档证明资料时间'
    }
    else if (val === 90) {
        // 补贴申领
        titleStr2.value = '申领补贴'
        labelStr.value = '申领补贴时间'
    }
    else if (val === 100) {
        // 补贴到账
        titleStr2.value = '补贴到账'
        labelStr.value = '补贴到账时间'
    }
})

// 进度
const { data: process, isLoading } = useApplyProcess(id)
watchEffect(() => {
    if (process.value && id.value) {
        // console.log('watchEffect process', process.value)
        stepData.value = cloneDeep(process.value).reduce((pre: any, cur: any, index: number) => {
            cur.step = cur.name

            cur.des = `${cur.finishTime ?? ''}${cur.operaName ? ' 操作人：' : ''} ${cur.operaName ?? ''}`
            if (cur.flag) {
                active.value = index + 1
            }
            pre.push(cur)
            return pre
        }, [])
        currentStatus.value = Number(status.value) + 10
        state.value.file = []

        setTimeout(() => {
            // 处理当前步骤显示
            const tempStatus = (Number(status.value) === Number(useDict('ProgressStatus', '补贴到账', false)) || Number(status.value) === Number(useDict('ProgressStatus', '审核不通过', false))) ? Number(status.value) : currentStatus.value
            const tempTarget = stepData.value.find((v: any) => v.status === tempStatus)
            handleStepClick(tempTarget)
        }, 200)
    }
})

watchEffect(() => {
    showFile()
})

function showFile() {
    if (currentStatus.value < Number(useDict('ProgressStatus', '补贴到账', false))) {
        // 文件模板处理，目前仅支持一个模板
        const item = stepData.value.find(item => item.status === currentStatus.value)
        currentFiles.value = item?.files || []
    }
    else if (Number(status.value) === Number(useDict('ProgressStatus', '补贴到账', false))) {
        const files = stepData.value[stepData.value.length - 1].info?.files
        if (files && files.length > 0) {
            state.value.file = files.reduce((pre: any, cur: any) => {
                if (!cur) {
                    cur = []
                }
                pre.push(cur)
                return pre
            }, [])
        }
    }
}

state.value = cloneDeep(initialState)

// 点击步骤节点
function handleStepClick(item) {
    // console.log('点击节点', item, 'status', status.value, 'currentStatus', currentStatus.value)
    state.value.info = ''
    state.value.formDate = ''
    state.value.file = []

    // 结束、不通过、未到的节点，不显示文件上传
    // item.status === Number(useDict('ProgressStatus', '完成业主意见征询', false)) ||
    if (item.status >= 300 || item.status > Number(status.value) + 10) {
        currentStatus.value = item.status
        return
    }

    // 已完成节点 + 进行中节点
    if (item.status <= Number(status.value) + 10) {
        currentStatus.value = item.status
        currentFiles.value = item.files
    }

    if (item.status <= Number(status.value)) {
        // 处理info
        if (item.info) {
            const info = item.info
            state.value.refuseType = info?.refuseType
            if (info?.files?.length > 0) {
                state.value.file = info.files.reduce((pre: any, cur: any) => {
                    if (!cur) {
                        cur = []
                    }
                    pre.push(toRaw(cur))
                    return pre
                }, [])
            }
            // console.log('点击节点', state.value.file)
        }
        else {
            state.value.file = []
        }
        state.value.result = item.result ? 1 : 0
        state.value.formDate = item.info?.formDate // 待看
        state.value.budget = item.info?.budget
        state.value.agentFlag = item.info?.agentFlag
        state.value.entranceFlag = item.info?.entranceFlag
        state.value.agentName = item.info?.agentName
        state.value.brand = item.info?.brand
        state.value.useCompany = item.info?.useCompany
        state.value.repairCompany = item.info?.repairCompany
        state.value.remark = item.info?.remark
        state.value.elevatorCode = item.info?.elevatorCode

        // console.log('info', state.value.file, item.info)
    }
}

// 提交表单
const { isPending, mutate } = useApplyAudit()

// 提交
async function submit() {
    // 联合审查单独给提示
    if (currentStatus.value === Number(useDict('ProgressStatus', '联合审查', false)) && (state.value.result === 1 && !state.value.budget)) {
        ElMessage.warning('请完善表单')
        return
    }

    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        // 文件判空（可行性分析、联合审查不通过是，不用判断）
        const isFile1 = (currentStatus.value === Number(useDict('ProgressStatus', '可行性分析', false))) && state.value.result === 1
        const isFile2 = (currentStatus.value === Number(useDict('ProgressStatus', '联合审查', false))) && state.value.result === 1
        const isFile3 = currentStatus.value === Number(useDict('ProgressStatus', '电梯使用登记', false))
        const isFile4 = currentStatus.value === Number(useDict('ProgressStatus', '竣工验收登记', false))
        const isFile5 = currentStatus.value === Number(useDict('ProgressStatus', '档案归档', false))
        if ((isFile1 || isFile2 || isFile3 || isFile4 || isFile5) && state.value.file.length === 0) {
            ElMessage.warning('请上传文件')
            return
        }

        doSubmit()
    }
}

function doSubmit() {
    // 改以前的，调更新接口
    const isOld = ref<boolean>(false)
    if (currentStatus.value <= Number(status.value)) {
        isOld.value = true
    }
    const info = {
        files: state.value.result ? state.value.file : [],
        refuseType: state.value.refuseType,
        remark: state.value.remark,
        formDate: (state.value.result && state.value.formDate) ? `${state.value.formDate} 00:00:00` : '',
        budget: state.value.result ? state.value.budget : null,
        agentFlag: state.value.agentFlag,
        entranceFlag: state.value?.entranceFlag,
        agentName: state.value.result ? state.value.agentName : '',
        brand: state.value.brand,
        useCompany: state.value.useCompany,
        repairCompany: state.value.repairCompany,
        elevatorCode: state.value.elevatorCode,
    }
    const params = {
        id: id.value ?? '',
        result: !!state.value.result,
        status: currentStatus.value || Number(status.value) + 10,
        info,
        isOld: isOld.value,
    }
    mutate(params, {
        onSuccess: () => {
            ElMessage.success('操作成功')
            cancel()
        },
    })
}

function cancel() {
    visible.value = false
    reset()
}

watch(() => visible.value, () => {
    if (!visible.value) {
        reset()
    }
})

function reset() {
    id.value = ''
    formRef.value.formInstance.resetFields()
    state.value.file = []
    state.value.result = 1
    state.value.refuseType = undefined
    state.value.formDate = ''
    currentStatus.value = 0
    position.value = {
        longitude: null,
        latitude: null,
    }
}

// 代办平台列表
function getApplyPlatList() {
    applyPlatList().then((res: any) => {
        platOptions.value = res.reduce((pre: any, cur: any) => {
            cur.label = cur.name
            cur.value = cur.code
            pre.push(cur)
            return pre
        }, [])
    })
}
getApplyPlatList()

const group: PlusFormGroupRow[] = [
    {
        title: '第一分组',
        hideInGroup: computed(() => (String(currentStatus.value) !== useDict('ProgressStatus', '可行性分析', false)) && String(currentStatus.value) !== useDict('ProgressStatus', '联合审查', false)),
        columns: [
            {
                label: '可行性分析结果',
                prop: 'result',
                hideInForm: computed(() => String(currentStatus.value) !== useDict('ProgressStatus', '可行性分析', false)),
            },
            {
                label: '联合审查意见',
                prop: 'result',
                hideInForm: computed(() => String(currentStatus.value) !== useDict('ProgressStatus', '联合审查', false)),
            },
            {
                label: '原因',
                prop: 'refuseType',
                hideInForm: computed(() => String(currentStatus.value) !== useDict('ProgressStatus', '可行性分析', false) || state.value.result === 1),
            },
        ],
    },
    {
        // (String(currentStatus.value) === useDict('ProgressStatus', '完成业主意见征询', false)) ||
        hideInGroup: computed(() => currentStatus.value > 300 || state.value.result !== 1),
        title: '第二分组',
        columns: [
            {
                colProps: {
                    span: 22,
                },
                fieldProps: {
                    'placeholder': '请选择时间',
                    'format': 'YYYY-MM-DD',
                    'type': 'date',
                    'valueFormat': 'YYYY-MM-DD',
                    'disabled-date': (time: Date) => {
                        return dayjs(time).isAfter(dayjs(new Date()).format('YYYY-MM-DD 23:59:59'))
                    },
                },
                // label: labelStr.value,
                label: computed(() => {
                    return labelStr.value
                }),
                prop: 'formDate',
                valueType: 'date-picker',
            },
            {
                label: '上传文件',
                prop: 'file',
                hasLabel: ref(false),
                // currentFiles.value.length === 0 ||
                hideInForm: computed(() => currentStatus.value >= Number(useDict('ProgressStatus', '审核不通过', false))),
            },
            {
                colProps: {
                    span: 22,
                },
                label: '电梯设备代码',
                prop: 'elevatorCode',
                hideInForm: computed(() => currentStatus.value !== Number(useDict('ProgressStatus', '电梯使用登记', false))),
            },
        ],
    },
    {
        hideInGroup: computed(() => (String(currentStatus.value) !== useDict('ProgressStatus', '联合审查', false)) && String(currentStatus.value) !== useDict('ProgressStatus', '电梯使用登记', false) || state.value.result !== 1),
        title: '其他',
        columns: [
            {
                colProps: {
                    span: 22,
                },
                label: '加装电梯工程预算（含建设工程质量相关检验检测费用）',
                prop: 'budget',
                hideInForm: computed(() => String(currentStatus.value) !== useDict('ProgressStatus', '联合审查', false)),
            },
            {
                colProps: {
                    span: 22,
                },
                label: '是否委托国有代办平台',
                options: [
                    {
                        label: '是',
                        value: 1,
                    },
                    {
                        label: '否',
                        value: 2,
                    },
                ],
                prop: 'agentFlag',
                valueType: 'radio',
                hideInForm: computed(() => String(currentStatus.value) !== useDict('ProgressStatus', '联合审查', false)),
            },
            {
                colProps: {
                    span: 22,
                },
                label: '是否平层入户',
                options: [
                    {
                        label: '是',
                        value: 1,
                    },
                    {
                        label: '否',
                        value: 2,
                    },
                ],
                prop: 'entranceFlag',
                valueType: 'radio',
                hideInForm: computed(() => String(currentStatus.value) !== useDict('ProgressStatus', '联合审查', false)),
            },
            {
                colProps: {
                    span: 22,
                },
                label: '代办平台',
                prop: 'agentName',
                valueType: 'select',
                options: computed(() => {
                    return platOptions.value
                }),
                hideInForm: computed(() => (String(currentStatus.value) !== useDict('ProgressStatus', '联合审查', false) || state.value.agentFlag === 2)),
            },
            {
                colProps: {
                    span: 22,
                },
                fieldProps: {
                    maxlength: 30,
                    showWordLimit: true,
                },
                label: '电梯品牌',
                prop: 'brand',
                hideInForm: computed(() => String(currentStatus.value) !== useDict('ProgressStatus', '电梯使用登记', false)),
            },
            {
                colProps: {
                    span: 22,
                },
                fieldProps: {
                    maxlength: 30,
                    showWordLimit: true,
                },
                label: '电梯使用单位',
                prop: 'useCompany',
                hideInForm: computed(() => String(currentStatus.value) !== useDict('ProgressStatus', '电梯使用登记', false)),
            },
            {
                colProps: {
                    span: 22,
                },
                fieldProps: {
                    maxlength: 30,
                    showWordLimit: true,
                },
                label: '电梯维保单位',
                prop: 'repairCompany',
                hideInForm: computed(() => String(currentStatus.value) !== useDict('ProgressStatus', '电梯使用登记', false)),
            },
        ],
    },
]

const reg = /^[a-z0-9]+$/i
function validatorpassword(rule, value, callback) {
    // 编辑忽略密码校验
    if (!!value && reg.test(value)) {
        callback()
    }
    else {
        callback(new Error('请输入数字和英文'))
    }
}
const rules = computed(() => ({
    elevatorCode: [
        {
            message: '请输入数字和英文',
            required: true,
            trigger: 'blur',
            validator: validatorpassword,
        },
    ],
    result: [
        {
            message: '请选择',
            required: true,
        },
    ],
    refuseType: [
        {
            message: '请选择原因',
            required: true,
        },
    ],
    formDate: [
        {
            message: '请选择时间',
            required: true,
        },
    ],
    budget: [
        {
            message: '请输入',
            required: true,
        },
    ],
    agentFlag: [
        {
            message: '',
            required: true,
        },
    ],
    entranceFlag: [
        {
            message: '',
            required: true,
        },
    ],
    brand: [
        {
            message: '',
            required: true,
        },
    ],
    useCompany: [
        {
            message: '',
            required: true,
        },
    ],
    repairCompany: [
        {
            message: '',
            required: true,
        },
    ],
    agentName: [
        {
            message: '请选择',
            required: true,
        },
    ],
}))
</script>

<template>
    <el-drawer v-model="visible"
               :size="1080"
    >
        <template #header>
            <div class="text-24 text-black font-600">
                {{ title }}
            </div>
        </template>

        <el-steps :active="active"
                  align-center
        >
            <el-step v-for="(item, index) in stepData"
                     :key="index"
                     :title="item.step"
                     :description="item.des"
                     @click="handleStepClick(item)"
            />
        </el-steps>

        <ElSkeleton v-if="isLoading"
                    animated
                    class="mt-20"
        />

        <template v-else>
            <div class="plusform mt-20">
                <!-- :has-footer="false" -->
                <!-- labelPosition="top" :columns="columns" -->
                <PlusForm ref="formRef"
                          v-model="state"
                          :group="group"
                          :label-width="400"
                          :rules="rules"
                          :row-props="{ gutter: 20 }"
                          :has-footer="false"
                >
                    <template #group-header="{ title }">
                        <div class="custom-group-header">
                            <span v-if="title === '第一分组'">{{ titleStr1 }}</span>

                            <span v-else-if="title === '第二分组'">{{ titleStr2 }}</span>

                            <span v-else>{{ title }}</span>
                        </div>
                    </template>

                    <template #plus-field-result>
                        <el-radio-group v-if="String(currentStatus) === useDict('ProgressStatus', '可行性分析', false)"
                                        v-model="state.result"
                                        :disabled="disabled"
                        >
                            <el-radio label="可行"
                                      :value="1"
                            />

                            <el-radio label="不可行"
                                      :value="0"
                            />
                        </el-radio-group>

                        <el-radio-group v-else
                                        v-model="state.result"
                                        :disabled="disabled"
                        >
                            <el-radio label="通过"
                                      :value="1"
                            />

                            <el-radio label="不通过"
                                      :value="0"
                            />
                        </el-radio-group>
                    </template>

                    <template #plus-field-refuseType>
                        <el-radio-group v-model="state.refuseType"
                                        class="radio-group"
                                        :disabled="disabled"
                        >
                            <el-radio label="不满足房屋结构安全要求"
                                      :value="1"
                            />

                            <el-radio label="不满足消防安全要求"
                                      :value="2"
                            />

                            <el-radio label="不满足城乡规划要求"
                                      :value="3"
                            />

                            <el-radio label="其他"
                                      :value="4"
                            >
                                其他：
                                <el-input v-model="state.remark"
                                          style="width: 500px"
                                          show-word-limit
                                          maxlength="30"
                                          placeholder="请输入原因"
                                          :disabled="disabled"
                                />
                            </el-radio>
                        </el-radio-group>
                    </template>

                    <template #plus-field-file>
                        <!-- 无模板：电梯使用登记、档案归档、补贴到账(非必填) -->
                        <div v-if="currentStatus === Number(useDict('ProgressStatus', '电梯使用登记', false)) || currentStatus === Number(useDict('ProgressStatus', '档案归档', false)) || currentStatus === Number(useDict('ProgressStatus', '补贴到账', false))"
                             class="mb-12 flex"
                        >
                            <div v-if="currentStatus === Number(useDict('ProgressStatus', '电梯使用登记', false))"
                                 class="required label-title"
                            >
                                电梯使用登记证
                            </div>

                            <div v-else-if="currentStatus === Number(useDict('ProgressStatus', '档案归档', false))"
                                 class="required label-title"
                            >
                                档案归档证明资料
                            </div>

                            <div v-else-if="currentStatus === Number(useDict('ProgressStatus', '补贴到账', false))"
                                 class="label-title pl10"
                            >
                                补贴凭证
                            </div>

                            <div>
                                <FlUpload :key="String(currentStatus)"
                                          v-model="state.file"
                                          :limit="10"
                                          accept="*"
                                          list-type="text"
                                          :tips="false"
                                />
                            </div>
                        </div>
                        <!-- 有模板 -->
                        <div v-else>
                            <div v-for="(item, index) in currentFiles"
                                 :key="index"
                                 class="mb-12 flex"
                            >
                                <div class="required"
                                     style="width: 400px;"
                                >
                                    <el-link class="link"
                                             style="color: #006DCC"
                                             :underline="false"
                                             :href="item.fileUrl"
                                    >
                                        {{ item.fileName }}下载
                                    </el-link>
                                </div>

                                <div>
                                    <FlUpload :key="String(currentStatus)"
                                              v-model="state.file"
                                              :limit="10"
                                              accept="*"
                                              list-type="text"
                                              :tips="false"
                                    />
                                </div>
                            </div>
                        </div>
                    </template>

                    <template #plus-field-budget>
                        <div class="flex">
                            <el-input v-model="state.budget"
                                      oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,4})?).*$/g, '$1')"
                            />

                            <div class="ml20 w100">
                                万元
                            </div>
                        </div>
                    </template>
                </plusform>
            </div>

            <!-- 地图 -->
            <div v-if="position?.longitude > 0"
                 class="abs"
            >
                <showMap v-model:longitude="position.longitude"
                         v-model:latitude="position.latitude"
                />
            </div>
        </template>

        <template #footer>
            <div class="flex: auto">
                <!-- && currentStatus!==30 -->
                <SubmitBtn v-if="currentStatus <= 150 && isEdit"
                           type="primary"
                           :loading="isPending"
                           @click="submit"
                >
                    {{ '提交' }}
                </SubmitBtn>

                <el-button @click="cancel">
                    取消
                </el-button>
            </div>
        </template>
    </el-drawer>
</template>

<style lang="scss" scoped>
.plusform {
    // height: 60vh;
    overflow-y: auto;
    overflow-x: hidden;
    .title {
        font-size: 16px;
        color: black;
    }
    .item {
        width: 90%;
        justify-content: space-between;
        height: 50px;
        line-height: 50px;
        .item-right {
            display: flex;
            align-items: center;
            .icon {
                color: rgb(2, 155, 0);
                font-size: 20px;
                margin-left: 6px;
            }
        }
    }
}

:deep(.el-step.is-center .el-step__description) {
    padding: 0;
}

:deep(.el-step__title) {
    font-size: 14px;
    word-break: break-all;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    padding: 0 2px;
    line-height: 20px;
    height: 40px;
    margin-top: 10px;
}

:deep(.el-step__head.is-finish .el-step__icon.is-text:hover) {
    color: #0381f7;
    border-color: #0381f7;
    cursor: pointer;
}

:deep(.el-step__head.is-process .el-step__icon.is-text:hover) {
    color: #0381f7;
    border-color: #0381f7;
    cursor: pointer;
}
:deep(.radio-group) {
    .el-radio {
        width: 100%;
        padding-left: 110px;
    }
}
:deep(.el-upload-list__item-file-name) {
    max-width: 200px;
}
.required:before {
    content: '* ';
    color: #f97316;
}
.label-title {
    width: 400px;
    color: #606266;
}
.abs {
    position: fixed;
    top: 20px;
    right: 1100px;
    background: #fff;
    width: calc(98vw - 1090px);
    height: 95vh;
}
</style>
